package com.lbs.utils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Administrator
 * @date 2021/5/29 10:01
 * @description
 **/
public class BaseDao<T> {

    QueryRunner runner = new QueryRunner();

    // 通用增删改
    public int update(String sql,Object...params){
        Connection connection = JdbcUtils.getConnection();
        try {
            return runner.update(connection, sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("操作失败"+e);
        } finally {
            JdbcUtils.CloseAll();
        }
    }

    // 通用查询单条语句
    public T findOne(String sql,Class clazz,Object...params){
        Connection connection = JdbcUtils.getConnection();
        try {
            return runner.query(connection,sql,new BeanHandler<T>(clazz),params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查询失败"+e);
        } finally {
            JdbcUtils.CloseAll();
        }
    }

    // 通用查询多条语句
    public List<T> findMore(String sql, Class clazz, Object...params){
        Connection connection = JdbcUtils.getConnection();
        try {
            return runner.query(connection,sql,new BeanListHandler<T>(clazz),params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查询失败"+e);
        } finally {
            JdbcUtils.CloseAll();
        }
    }

    // 通用查询聚合函数语句
    public T findScalar(String sql,Object...params){
        Connection connection = JdbcUtils.getConnection();
        try {
            return runner.query(connection, sql, new ScalarHandler<>(), params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查询失败"+e);
        } finally {
            JdbcUtils.CloseAll();
        }
    }

}
